const express = require('express');
const mysql = require('mysql2');
const cors = require('cors');
const bodyParser = require('body-parser');

const app = express();
const port = 3000;

app.use(cors());
app.use(bodyParser.json());

// 数据库连接
const db = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '123456',
  database: 'donation_platform'
});

db.connect(err => {
  if (err) throw err;
  console.log('数据库连接成功');
});

// 接收虚拟数据写入数据库
app.post('/api/save-projects', (req, res) => {
  const p = req.body;
  const sql = `INSERT INTO hot_projects (
    id, name, shortDescription, description, image,
    goal, raised, progress, donors, tag, status, walletAddress
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;

  const values = [
    p.id, p.name, p.shortDescription, p.description, p.image,
    p.goal, p.raised, p.progress, p.donors, p.tag, p.status, p.walletAddress
  ];

  db.query(sql, values, (err) => {
    if (err) {
      console.error(err);
      res.status(500).send('保存失败');
    } else {
      res.send('保存成功');
    }
  });
});

// 获取所有项目
app.get('/api/hot-projects', (req, res) => {
  const sql = 'SELECT * FROM hot_projects';
  db.query(sql, (err, results) => {
    if (err) {
      console.error('❌ 获取数据失败:', err);
      res.status(500).send('服务器内部错误');
    } else {
      res.json(results);
    }
  });
});



app.listen(port, () => {
  console.log(`后端服务运行在 http://localhost:${port}`);
});
